﻿using _2._23._2015_GroceryList.Data;
using _2._23._2015_GroceryList.Data.Models;
using _2._23._2015_GroceryList.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2._23._2015_GroceryList.Adapters
{
    /// <summary>
    /// Grocery Items Enity Framework Repository
    /// </summary>
    public class GroceryItemsDataAdapter : IGroceryItemsAdapter
    {
        public List<GroceryItemViewModel> GetGroceryItems()
        {
            List<GroceryItemViewModel> models = null;

            using (GroceryListDbContext db = new GroceryListDbContext())
            {
                models = db.GroceryItems.Select(i => new GroceryItemViewModel
                {
                    DatePurchased = i.DatePurchased,
                    GroceryItemId = i.GroceryItemId,
                    ItemName = i.ItemName,
                    ItemPrice = i.ItemPrice,
                    Quantity = i.Quantity,
                    TypeId = i.GroceryItemTypeId,
                    TypeName = i.Type.Name
                }).ToList();
            }

            return models;
        }

        public DateTime? PurchaseGroceryItem(int id)
        {
            try
            {
                DateTime datePurchased = DateTime.UtcNow;

                using (GroceryListDbContext db = new GroceryListDbContext())
                {
                    GroceryItem item = db.GroceryItems.Find(id);
                    item.DatePurchased = datePurchased;
                    db.SaveChanges();
                }

                return datePurchased;
            }
            catch
            {
                return null;
            }
        }

        public int AddItem(GroceryItemViewModel model, string userId)
        {
            int groceryItemId;

            using (GroceryListDbContext db = new GroceryListDbContext())
            {
                GroceryItem item = new GroceryItem
                {
                    ItemName = model.ItemName,
                    ItemPrice = model.ItemPrice,
                    Quantity = model.Quantity,
                    UserId = userId,
                    GroceryItemTypeId = model.TypeId
                };

                db.GroceryItems.Add(item);
                db.SaveChanges();

                groceryItemId = item.GroceryItemId;
            }

            return groceryItemId;
        }
    }
}
